package com.zhiketuan.webserver.service;

import com.zhiketuan.webserver.mapper.SysAdminDao;
import com.zhiketuan.webserver.domain.SysAdmin;
import com.zhiketuan.webserver.model.ResponseResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class SysAdminService {

    private static final Logger logger = Logger.getLogger(SysAdminService.class);

    @Autowired
    private SysAdminDao sysAdminDao;

    public ResponseResult saveSysAdmin(SysAdmin sysAdmin) {

        ResponseResult result = ResponseResult.ok(null);

        try {
            sysAdminDao.save(sysAdmin);
            result.setData(sysAdmin);
            result.setMessage("保存新管理员成功");
        } catch (Exception e) {
            logger.error("Save system admin info failed.", e);
            result = ResponseResult.error(e.getLocalizedMessage());
        }

        return result;
    }

    public ResponseResult updateSysAdmin(SysAdmin sysAdmin) {

        ResponseResult result = ResponseResult.ok(null);

        try {
            sysAdminDao.update(sysAdmin);
            result.setData(sysAdmin);
            result.setMessage("更新管理员成功");
        } catch (Exception e) {
            logger.error("Update system admin info failed.", e);
            result = ResponseResult.error(e.getLocalizedMessage());
        }

        return result;
    }

    public ResponseResult deleteSysAdmin(Integer adminId) {

        ResponseResult result = ResponseResult.ok(null);

        try {
            sysAdminDao.delete(adminId);
            result.setMessage("删除管理员成功");
        } catch (Exception e) {
            logger.error("Update system admin info failed.", e);
            result = ResponseResult.error(e.getLocalizedMessage());
        }

        return result;
    }

    public ResponseResult searchSysAdminByAct(String account) {

        ResponseResult result = ResponseResult.ok(null);

        try {
            SysAdmin sysAdmin = sysAdminDao.findByAct(account);
            sysAdmin.setPassword(null);
            result.setData(sysAdmin);
        } catch (Exception e) {
            logger.error("Search system admin info failed.", e);
            result = ResponseResult.error(e.getLocalizedMessage());
        }

        return result;
    }
}
